package com.Jhu1.service.impl;

import cn.hutool.core.util.StrUtil;
import com.Jhu1.entity.Product;
import com.Jhu1.entity.Type;
import com.Jhu1.mapper.ProductMapper;
import com.Jhu1.service.IProductService;
import com.Jhu1.service.ITypeService;
import com.Jhu1.util.PageResult;
import com.Jhu1.vo.ProductVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 钟俊辉
 * @since 2025-01-11
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ITypeService typeService;

    @Override
    public PageResult<Product> findByPage(Integer page, Integer pageSize) {
        // 获取分页数据
        Page<Product> page_first = this.page(new Page<>(page, pageSize));

        // 返回分页结果
        return new PageResult<>(page_first.getRecords(), page_first.getTotal());
    }

    @Override
    public PageResult<Product> searchProduct(Integer page, Integer pageSize, ProductVO vo) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();

        // 根据产品名称模糊查询
        wrapper.like(StrUtil.isNotBlank(vo.getPname()), "pname", vo.getPname());

        // 判断并添加价格区间的条件：priceMin 和 priceMax
        if (vo.getPriceMin() != null) {
            wrapper.ge("price", vo.getPriceMin()); // 大于等于 priceMin
        }
        if (vo.getPriceMax() != null) {
            wrapper.le("price", vo.getPriceMax()); // 小于等于 priceMax
        }

        // 根据类别ID进行查询，tid为0表示不需要该条件
        wrapper.eq(vo.getTid() != 0, "tid", vo.getTid());

        // 分页查询
        Page<Product> page1 = this.page(new Page<>(page, pageSize), wrapper);

        // 设置每个产品的类别名称
        page1.getRecords().forEach(pd -> {
            if (pd.getTid() != null) {
                Type types = typeService.getById(pd.getTid());
                if (types != null) {
                    pd.setTname(types.getTname());  // 设置类别名称
                }
            }
        });

        // 返回分页结果
        return new PageResult<>(page1.getRecords(), page1.getTotal());
    }


}
